const { sign } = require('jsonwebtoken');
const useCaptcha = require('../utils/useCaptcha');
const DB = require('../modules/db');
const secret = require('../modules/jwt');

const captcha = new useCaptcha();

// 用户详情
const userDetail = async ctx => {
  try {
    ctx.body = {
      msg: 'token鉴权通过',
      username: ctx.state.user.username
    }
  } catch (error) {
    ctx.throw(error);
  }
};
// 获取验证码
const getCaptchaCode = async ctx => {
  // ctx.request.params URL路径参数
  // ctx.request.query 请求参数  http://localhost:3000/api/login?name=123&age=123
  // ctx.request.header 头参数
  // ctx.request.body json对象参数
  try {
    const { data } = captcha.initCaptcha();
    ctx.body = {
      success: true,
      code: 200,
      msg: '获取验证码成功',
      uuid: ctx.uuid,
      token: captcha.bufferToken,
      data
    };
  }
  catch (error) {
    ctx.throw(error);
  }
};

// 注册
const register = async ctx => {
  try {

    const { username, password, captchaCode } = ctx.request.body;
    // 验证码是否正确
    if (captchaCode.toLocaleLowerCase() === captcha.bufferToken.toLocaleLowerCase()) {

      const sql = `INSERT INTO user(username, password) VALUES ('${username}', '${password}');`;

      await DB.query(sql);

      ctx.body = {
        code: 200,
        msg: '注册成功',
        success: true
      };
    }
    else {
      ctx.body = {
        code: 200,
        msg: '注册失败，验证码错误',
        success: false
      };
    }
    
  }
  catch (error) {
    ctx.throw(error);
  }
};

// 登录
const login = async ctx => {
  try {

    const { username, password, captchaCode } = ctx.request.body;

    // 验证码是否正确
    if (captchaCode.toLocaleLowerCase() === captcha.bufferToken.toLocaleLowerCase()) {

      const sql = `select * from user`;
      const userList = await DB.query(sql);
      // 查找账户
      const user = userList.find(item => item.username === username);

      // 用户存在
      if (!!user) {
        
        // 密码正确
        if (user.password === password) {
          // 签发令牌 token
          const token = sign(
            {
              username
            },
            secret,
            {
              expiresIn: '1h'
            }
          );
          ctx.body = {
            code: 200,
            msg: '登录成功',
            token: token,
            success: true
          };
        }
        // 密码错误
        else {
          ctx.body = {
            code: 200,
            msg: '密码错误',
            success: false
          };
        }
        
      }
      else {
        ctx.body = {
          code: 200,
          msg: '该账号不存在，请注册后再登录',
          success: false
        };
      }
    }
    // 验证码错误
    else {
      ctx.body = {
        code: 200,
        msg: '验证码错误',
        success: false
      };
    }
  }
  catch (error) {
    ctx.throw(error);
  }
};



module.exports = {
  userDetail,
  getCaptchaCode,
  register,
  login
};